﻿using System.Reflection;
using Basmus.Conel;

namespace Basmus.Values.Attributive
{
    public class BindingBuilder : IBindingBuilder
    {
        private readonly IBinder _binder;
        private readonly IPropertyInfoBuilder _propertyInfoBuilder;

        public BindingBuilder(IBinder binder, IPropertyInfoBuilder propertyInfoBuilder)
        {
            _binder = binder;
            _propertyInfoBuilder = propertyInfoBuilder;
        }

        public Binding Build(ValuesContext valuesContext)
        {
            var info = _propertyInfoBuilder.Build(valuesContext);
            if (info != null)
            {
                var elementTypeAttribute =
                    info.GetKeyAttributeOrDefaultKeyAttribute<PropertyInfo, ElementTypeAttribute>(valuesContext.ModelContext.SchemeKey, false);
                if (elementTypeAttribute != null)
                {
                    return _binder.Bind(info, elementTypeAttribute.ElementType);
                }
                return _binder.Bind(info);
            }
            return null;
        }

        
    }
}